import React, { useState } from 'react';
import { View, Text } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { Input, Button, Toast } from '@nutui/nutui-react-taro';
import { login } from '../../services/user';
import './index.scss';

const Login: React.FC = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading] = useState(false);
  const [showToast, setShowToast] = useState(false);
  const [toastMessage, setToastMessage] = useState('');

  const handleLogin = async () => {
    if (!username.trim()) {
      setToastMessage('请输入用户名');
      setShowToast(true);
      return;
    }

    if (!password) {
      setToastMessage('请输入密码');
      setShowToast(true);
      return;
    }

    try {
      setLoading(true);
      const response = await login({ username, password });
      Taro.setStorageSync('token', response.token);
      Taro.setStorageSync('userInfo', response.user);
      Taro.reLaunch({ url: '/pages/index/index' });
    } catch (error) {
      setToastMessage(error.message || '登录失败');
      setShowToast(true);
    } finally {
      setLoading(false);
    }
  };

  const goToRegister = () => {
    Taro.navigateTo({ url: '/pages/register/index' });
  };

  return (
    <View className="login-container">
      <View className="login-header">
        <Text className="login-title">登录</Text>
        <Text className="login-subtitle">欢迎回来，请登录您的账号</Text>
      </View>
      
      <View className="login-form">
        <View className="form-item">
          <Input 
            className="input"
            placeholder="用户名"
            value={username}
            onChange={(value) => setUsername(value)}
          />
        </View>
        
        <View className="form-item">
          <Input 
            className="input"
            placeholder="密码"
            type="password"
            value={password}
            onChange={(value) => setPassword(value)}
          />
        </View>
        
        <Button 
          type="primary" 
          block
          loading={loading}
          className="login-button"
          onClick={handleLogin}
        >
          登录
        </Button>
        
        <View className="register-link" onClick={goToRegister}>
          <Text>还没有账号？点击注册</Text>
        </View>
      </View>
      
      <Toast
        visible={showToast}
        content={toastMessage}
        onClose={() => setShowToast(false)}
        type="warn"
        duration={2000}
      />
    </View>
  );
};

export default Login; 